<template>
  <ly-dialog
    v-model="visible"
    title="余下--新增"
    width="1250px"
    fullscreen
    :confirm="handleConfirm"
    :cancel="handleCancel"
    :before-close="() => {$emit('update:visible', false)}"
    @open="handleOpen"
  >
    <template #operation>
      <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="handlePush()"
      >增加一行</el-button>
      <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="handleCopy()"
      >复制一行</el-button>
      <el-button
        type="primary"
        icon="el-icon-delete"
        class="deleted-button"
        @click="handleBatchDelete()"
      >
        批量删除
      </el-button>
    </template>
    <ly-form
      size="mini"
      class="mini-form"
      style="width:100%"
      :model="temp"
      @submit.native.prevent
    >
      <el-row>
        <el-col :span="5">
          <el-form-item
            label="平台"
            prop="platform"
          >
            <el-select
              v-model="temp.platform"
              clearable
              placeholder="请选择平台"
              @change="handleChange"
            >
              <el-option
                v-for="item in platformList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item
            label="修改日期"
            prop="modifyTime"
          >
            <el-date-picker
              v-model="temp.modifyTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </ly-form>
    <client-table
      ref="table"
      :style="{ height: `${commonLayoutHeight}px`}"
      :columns="remainAddColumnDef"
      :data="tableData"
      show-summary
      @selection-change="handleSelectionChange"
      @cell-value-changed="handleCellValueChanged"
    />
  </ly-dialog>
</template>

<script>
import { mapState } from 'vuex'
import { addOne } from '@/api/information'
import moment from 'moment'

export default {
  name: 'RemainAddDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: undefined
    },
    platformList: {
      type: Array,
      default: undefined
    }
  },
  data() {
    return {
      temp: {
        modifyTime: '',
        platform: '',
        platformName: ''
      },
      restTemp: {
        modifyTime: '',
        platform: '',
        platformName: ''
      },
      tableData: [],
      multipleSelection: [],
      multipleNodeSelection: [],
      remainAddColumnDef: [
        {
          headerName: '余下日期',
          field: 'orderDate',
          singleClickEdit: true,
          headerClass: 'my-class',
          type: 'monthColumn'
        },
        {
          headerName: '本月余下金额',
          field: 'incomePrice',
          showSummary: true,
          headerClass: 'my-class',
          type: 'numberColumn'
        },
        {
          headerName: '上月余下金额',
          field: 'remainPrice',
          showSummary: true,
          headerClass: 'my-class',
          type: 'numberColumn'
        },
        {
          headerName: '备注',
          field: 'remarks',
          singleClickEdit: true,
          type: 'stringColumn'
        }
      ]
    }
  },
  computed: {
    ...mapState('app', {
      commonLayoutHeight: state => state.height.clientHeight - 190
    })
  },
  watch: {
  },
  methods: {
    handleOpen() {
      this.tableData = []
      this.temp = Object.assign({}, this.restTemp)
      setTimeout(() => {
        this.handlePush('add')
      }, 200)
      // 键盘绑定事件
      const that = this
      document.addEventListener('keydown', that.bindingKeydown)
    },
    async handleConfirm() {
      this.$refs.table.redrawRows()
      const remainLists = this.$refs.table.getData()
      const list = this.multipleSelection.filter(item => item.remainPrice === '' || item.remainPrice === null)
      if (list.length > 0) {
        return this.$message({
          showClose: true,
          message: '必选项未填！！！',
          type: 'warning',
          center: true
        })
      }
      this.temp.remainLists = remainLists
      const result = await addOne('getRemainAdd', this.temp)
      if (result.code === 200) {
        this.setVisible(false)
        this.$notify({
          title: '成功',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
        setTimeout(() => {
          this.$emit('add-data')
        }, 300)
      }
    },
    // 下键事件
    bindingKeydown(event) {
      if (event.code === 'ArrowDown') {
        this.handleCopy()
      }
    },
    // 新增
    handlePush(val) {
      const addRow = this.remainAddColumnDef.reduce((acc, curr) => {
        acc[curr.field] = ''
        return acc
      }, {})
      const addRows = [addRow]
      addRows[0].incomePrice = 0
      addRows[0].remainPrice = 0
      if (val === 'add') {
        addRows[0].orderDate = moment().format('YYYY-MM')
      }
      if (this.multipleSelection.length > 0) {
        const tableData = this.$refs.table.addRowsIndex(this.$refs.table, addRow, this.multipleNodeSelection.rowIndex)
        this.tableData = tableData
      } else {
        this.$refs.table.addRows(addRows)
      }
      this.$refs.table.redrawRows()
      this.$refs.table.selectRow(addRow)
    },
    // 复制
    handleCopy() {
      const addRow = Object.assign({}, this.multipleSelection[0])
      const addRows = [addRow]
      this.$refs.table.addRows(addRows)
      this.$refs.table.redrawRows()
      this.$refs.table.selectRow(addRow)
      this.$refs.table.syncSummaryRow(this.$refs.table.getData())
    },
    // 双击修改
    handleCellValueChanged() {
      this.$refs.table.syncSummaryRow(this.$refs.table.getData())
    },
    // 删除
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          showClose: true,
          message: '请勾选要删除项',
          type: 'warning',
          center: true
        })
        return
      }
      this.$refs.table.removeRows(this.multipleSelection)
      this.$refs.table.syncSummaryRow(this.$refs.table.getData())
    },
    handleSelectionChange(val, node) {
      this.multipleSelection = val
      this.multipleNodeSelection = node[0]
    },
    handleChange(val) {
      const list = this.platformList.filter(item => item.id === val)
      if (list.length > 0) {
        this.temp.platformName = list[0].name
      }
    },
    handleCancel() {
      this.setVisible(false)
    },
    setVisible(flag) {
      this.$emit('update:visible', flag)
    }
  }
}
</script>

<style>
</style>
